<script setup lang="ts">
import type { VxePagerEvents } from 'vxe-table'

import { closeOrder, exportOrder, getOrderRefundState, getPaymentOrderState, listBase, releaseHousingResources } from '@fl/api/order/base'
import { useStoreDict } from '@fl/store/modules/goodHouseDict'

import type { IForm, OrderObject } from './types'

import orderCancelDialog from '../cancel.vue'
import orderDialog from '../details.vue'
import editHomebuyer from '../editHomebuyer.vue'
import peopleDialog from '../people.vue'
import DictTag from '../components/DictTag/index.vue'
import { useForm } from './hooks/use-form'
import { useTable } from './hooks/use-table'

const { gridOptions } = useTable()
const { form, schema, state } = useForm()

const dictStore = useStoreDict()
dictStore.init(['order_ddzt', 'order_zffs', 'order_shzt'])
const { getDicts } = storeToRefs(dictStore)

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const peopleDialogVisible = ref(false)
const peopleDetailsForm = ref({})
const houseCustomId = ref('')
const orderDetailsDialogVisible = ref(false)
const orderDetailsForm = ref({})
const editVisible = ref(false)
const buyerId = ref('')
const refundMethod = ref('')
const orderQxDialogVisible = ref(false)
const exportLoading = ref(false)

function getList() {
    gridOptions.loading = true
    const { cancelTime, createTime, projectBaseId, ...rest } = form.value
    const oParams: IForm = {
        pageNum: tablePage.currentPage,
        pageSize: tablePage.pageSize,
        projectBaseId: projectBaseId || '',
        ...rest,
    }
    if (createTime) {
        oParams.timeStart = createTime[0]
        oParams.timeEnd = createTime[1]
    }
    if (cancelTime) {
        oParams.cancellationTimeStart = cancelTime[0]
        oParams.cancellationTimeEnd = cancelTime[1]
    }

    listBase(oParams)
        .then((res) => {
            const { rows, total } = res
            tablePage.total = total
            gridOptions.data = rows
        })
        .catch((err) => {
            console.log('错误：：', err)
        })
        .finally(() => {
            gridOptions.loading = false
        })
}
getList()

function search() {
    tablePage.currentPage = 1
    getList()
}

function reset() {
    form.value = {
        ...state,
    }
    tablePage.currentPage = 1
    tablePage.pageSize = 10
    getList()
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    getList()
}

// 同步订单退款状态
function handleRefreshState(id: string) {
    getPaymentOrderState({ id }).then((res) => {
        if(res?.code === 200){
            ElMessage.success('同步成功')
            getList()
        }else{
            ElMessage.error(res?.msg || '操作失败')
        }
    })
}

// 同步订单退款状态
function handleRefreshRefundState(id: string) {
    getOrderRefundState({ id }).then((res) => {
        if(res?.code === 200){
            ElMessage.success('同步成功')
            getList()
        }else{
            ElMessage.error(res?.msg || '操作失败')
        }
    })
}

// 关闭订单按钮
function handleClose(row) {
    ElMessageBox.confirm(`是否关闭"${row.userName}"的定金订单?`, '提示', {
        type: 'warning',
    }).then(() => {
        closeOrder(row.id).then((res) => {
            if(res?.code === 200){
                ElMessage.success('关闭成功')
                getList()
            }else{
                ElMessage.error(res?.msg || '操作失败')
            }
        })
    })
}

// 释放房源按钮
function handleSffy(row) {
    const _ids = row.id
    ElMessageBox.confirm(`确认释放订单的房源\'${row.fyxx}\'，释放后房源状态为未上架状态?`, '提示', {
        type: 'warning',
    }).then(() => {
        releaseHousingResources({ id: _ids }).then((res) => {
            if(res?.code === 200){
                ElMessage.success('释放成功')
                getList()
            }else{
                ElMessage.error(res?.msg || '操作失败')
            }
        })
    })
}
// 取消(弹框)
function openOrderQxDialog(row, type) {
    orderDetailsForm.value = row
    refundMethod.value = type
    orderQxDialogVisible.value = true
}

// 关闭dialogQx
function orderQxDialogHandleClose() {
    orderQxDialogVisible.value = false
    getList()
}

// 显示用户详情
function openPeopleDetail(row) {
    houseCustomId.value = row.houseCustomId
    peopleDialogVisible.value = true
    peopleDetailsForm.value = row
}

// 关闭peopleDialog
function peopleDialogHandleClose() {
    peopleDialogVisible.value = false
}

// 查看订单按钮(弹框)
function openOrderDetailsDialog(row) {
    orderDetailsForm.value = row
    orderDetailsDialogVisible.value = true
}

// 关闭dialog
function orderDetailsDialogHandleClose() {
    orderDetailsDialogVisible.value = false
    getList()
}

// 弹出编辑购房人弹框
function openEditHomebuyer(id: string) {
    buyerId.value = id
    editVisible.value = true
}

// 关闭编辑购房人弹框
function editHomebuyerHandleClose() {
    editVisible.value = false
    buyerId.value = ''
}

function handleExport() {
    const { cancelTime, createTime, projectBaseId, ...rest } = form.value
    const params: IForm = {
        pageNum: tablePage.currentPage,
        pageSize: tablePage.pageSize,
        projectBaseId: projectBaseId || '',
        ...rest,
    }
    if (createTime) {
        params.timeStart = createTime[0]
        params.timeEnd = createTime[1]
    }
    if (cancelTime) {
        params.cancellationTimeStart = cancelTime[0]
        params.cancellationTimeEnd = cancelTime[1]
    }
    exportLoading.value = true
    exportOrder(params).then((res) => {
        const url = window.URL.createObjectURL(new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', `订单综合查询表_${new Date().getTime()}.xlsx`)
        document.body.appendChild(link)
        link.click()
    }).finally(() => {
        exportLoading.value = false
    })
}
</script>

<template>
    <ElCard class="mb-20">
        <PlusForm v-model="form"
                  :columns="schema"
                  :row-props="{ gutter: 20 }"
                  label-width="80"
                  label-position="right"
        >
            <template #footer>
                <div class="ml-auto">
                    <el-button type="primary"
                               icon="Search"
                               @click="search"
                    >
                        搜索
                    </el-button>

                    <el-button icon="Refresh"
                               @click="reset"
                    >
                        重置
                    </el-button>

                    <el-button type="warning"
                               v-hasPermi="['order:base:export']"
                               plain
                               icon="Download"
                               @click="handleExport"
                               :loading="exportLoading"
                    >
                        导出
                    </el-button>
                </div>
            </template>
        </PlusForm>
    </ElCard>

    <ElCard>
        <vxe-grid v-bind="gridOptions">
            <template #userName="{ row }">
                <el-button type="primary"
                           link
                           @click="openPeopleDetail(row)"
                >
                    {{ row.userName }}
                </el-button>
            </template>

            <template #paymentMethod="{ row }">
                <DictTag :options="getDicts.order_zffs" :value="row.paymentMethod"  />
            </template>

            <template #status="{ row }">
                <DictTag :options="getDicts.order_ddzt" :value="row.status"  />
            </template>

            <template #shzt="{ row }">
                <DictTag :options="getDicts.order_shzt" :value="row.shzt"  />
            </template>

            <template #eszt="{ row }">
                <DictTag :options="getDicts.order_shzt" :value="row.eszt"  />
            </template>

            <template #operate="{ row }">
                <el-button type="primary"
                           v-hasPermi="['order:base:query']"
                           link
                           @click="openOrderDetailsDialog(row)"
                >
                    查看
                </el-button>

                <span style="margin: 0px 6px; color: #e4e7ed">|</span>

                <el-popover placement="top-start"
                            trigger="hover"
                            width="86px"
                >
                    <div class="popoverBox">
                        <el-button link
                                   type="primary"
                                   v-hasPermi="['order:base:refreshOrderState']"
                                   @click="handleRefreshState(row.id)"
                        >
                            订单状态同步
                        </el-button>

                        <el-button link
                                   type="primary"
                                   v-hasPermi="['order:base:refreshRefundState']"
                                   @click="handleRefreshRefundState(row.id)"
                        >
                            订单退款状态同步
                        </el-button>

                        <el-button v-show="row.status === '1'"
                                   link
                                   type="primary"
                                   v-hasPermi="['order:base:editGb']"
                                   @click="handleClose(row)"
                        >
                            关闭
                        </el-button>

                        <el-button v-show="(row.houseState === '01' || row.houseState === '10' || row.houseState === '30') && (row.status === '2' || row.status === '3') && row.allowedRefund === '1'"
                                   link
                                   type="primary"
                                   v-hasPermi="['order:base:releaseHousingResources']"
                                   @click="handleSffy(row)"
                        >
                            释放房源
                        </el-button>

                        <template v-if="row.houseState === '01' || row.houseState === '10' || row.houseState === '30'">
                            <el-button v-show="row.refundMethod === null && row.status === '2' && row.allowedRefund === '0'"
                                       link
                                       type="primary"
                                       v-hasPermi="['order:base:editQx']"
                                       @click="openOrderQxDialog(row, '2')"
                            >
                                取消订单
                            </el-button>

                            <el-button v-show="row.refundMethod === null && row.status === '2' && row.allowedRefund === '0'"
                                       link
                                       type="primary"
                                       v-hasPermi="['order:base:editYjtk']"
                                       @click="openOrderQxDialog(row, '1')"
                            >
                                一键退款
                            </el-button>

                            <el-button v-show="row.status === '2'"
                                       link
                                       type="primary"
                                       v-hasPermi="['order:customLog:add']"
                                       @click="openEditHomebuyer(row.id)"
                            >
                                编辑购房人
                            </el-button>
                        </template>
                    </div>

                    <template #reference>
                        <el-button link
                                   type="primary"
                        >
                            更多
                        </el-button>
                    </template>
                </el-popover>
            </template>

            <template #pager>
                <vxe-pager :current-page="tablePage.currentPage"
                           :page-size="tablePage.pageSize"
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           background
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </ElCard>
    <!-- 用户详情 -->
    <el-dialog v-model="peopleDialogVisible"
               width="50%"
               append-to-body
               destroy-on-close
    >
        <template #header>
            <p class="dialogheader">
                用户详情
            </p>
        </template>

        <peopleDialog :house-custom-id="houseCustomId"
                      :handle-close="peopleDialogHandleClose"
                      :people-details-form="peopleDetailsForm"
        />
    </el-dialog>

    <!-- 订单详情 -->
    <el-dialog v-model="orderDetailsDialogVisible"
               width="80%"
               :before-close="orderDetailsDialogHandleClose"
               append-to-body
               destroy-on-close
    >
        <template #header>
            <p class="dialogheader">
                订单详情
            </p>
        </template>
        <!-- 订单详情 -->
        <orderDialog :order-details-form="orderDetailsForm"
                     :handle-close="orderDetailsDialogHandleClose"
        />
    </el-dialog>

    <!-- 取消申请 -->
    <el-dialog v-model="orderQxDialogVisible"
               width="60%"
               :before-close="orderQxDialogHandleClose"
               append-to-body
               destroy-on-close
    >
        <template #header>
            <p class="dialogheader">
                取消订单
            </p>
        </template>
        <!-- 取消申请 -->
        <orderCancelDialog :order-details-form="orderDetailsForm"
                           :refund-method="refundMethod"
                           :handle-close="orderQxDialogHandleClose"
        />
    </el-dialog>

    <!-- 编辑购房人 -->
    <el-dialog v-model="editVisible"
               width="60%"
               :before-close="editHomebuyerHandleClose"
               append-to-body
               destroy-on-close
    >
        <template #header>
            <p class="dialogheader">
                编辑购房人
            </p>
        </template>
        <!-- 编辑购房人 -->
        <editHomebuyer :id="buyerId"
                       :is-disabled="false"
                       :handle-close="editHomebuyerHandleClose"
        />
    </el-dialog>
</template>

<style scoped lang="scss">
:deep(.el-popover.el-popper) {
    min-width: 86px !important;
}
.popoverBox {
    .el-button {
        margin-left: 0 !important;
        margin-bottom: 12px;
        display: block;
    }
    .el-button:last-child {
        margin-bottom: 0;
    }
}
</style>
